<?php

namespace app\admin\service\common;

use app\admin\model\admin\Notice as NoticeModel;
use app\common\Constants;
use mqtt\MQTTService;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;

class NoticeService
{
    public static function publishNotice($id): void
    {
        try {
            $noticeInfo = NoticeModel::with('sender')->find($id);
            $instance_id = config('instance.instance_id');
            if (!$instance_id) {
                throw new ValidateException('未初始化系统标识，请先初始化系统标识！');
            }

            $payload = [
                'sender' => $noticeInfo->sender->username,
                'title' => $noticeInfo->title,
                'content' => $noticeInfo->content,
                'date' => date('Y-m-d H:i:s'),
                'scope'  => ($noticeInfo->category == 1) ? 'sys' : 'dept'
            ];

            if ($noticeInfo->category == 1) {
                $topics[] = "instance/{$instance_id}/sys/notice";
            } else {
                foreach ($noticeInfo->target as $target) {
                    $topics[] = "instance/{$instance_id}/dept/notice/{$target}";
                }
            }

            $mqtt = new MqttService();
            foreach ($topics as $topic) {
                $mqtt->publish($topic, $payload, false);
            }
        } catch (\Exception $e) {
            throw $e;
        }
    }
}